package cn.itsource.common.controller;

import cn.itsource.common.query.BaseQuery;
import cn.itsource.common.service.BaseService;
import cn.itsource.common.util.AjaxResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

public class BaseController<T> {
    @Autowired
    private BaseService<T> baseService;



    @PutMapping
    @ApiOperation("保存")
    public AjaxResult save(@RequestBody T t){
        try{
            baseService.save(t);
            return AjaxResult.me().setSuccess(true).setMessage("保存成功");
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("保存失败");
        }
    }
    @PostMapping
    @ApiOperation("修改")
    public AjaxResult update(@RequestBody T t){
        try{
            baseService.update(t);
            return AjaxResult.me().setSuccess(true).setMessage("修改成功");
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try{
            baseService.deleteById(id);
            return AjaxResult.me().setSuccess(true).setMessage("删除成功");
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }


    /**
     * 批量删除
     * @param list
     * @return
     */
    @PatchMapping("/batchDelete")
    public AjaxResult batchDelete(@RequestBody List<Long> list){
        try{
            baseService.batchDelete(list);
            return AjaxResult.me()
                    .setSuccess(true);
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("查询失败");
        }
    }

    /**
     * 分页查询
     * @param query  查询条件
     * @return
     */
    @PatchMapping
    public AjaxResult queryPage(@RequestBody BaseQuery query ){
        try{

            return AjaxResult.me()
                    .setSuccess(true)
                    .setResultObj(baseService.findPageList(query));
        }catch (Exception e){
            e.printStackTrace() ;
            return AjaxResult.me().setSuccess(false).setMessage("查询失败");
        }
    }



}
